<template>
  <div class="account-page">
    <!-- 账户余额概览 -->
    <div class="balance-card">
      <div class="balance-header">账户余额</div>
      <div class="balance-amount">¥{{ self.role === 1 ? formatAmount(self.balance) : formatAmount(Number(self.weijiesuan)
        +
        Number(self.dongjie)) }}</div>
      <div class="balance-details" v-if="self.role === 2">
        <div class="detail-item" v-if="self.role === 2">
          <span>未结算余额</span>
          <span>¥{{ formatAmount(self.weijiesuan || 0) }}</span>
        </div>
        <div class="detail-item" v-if="self.role === 2">
          <span>冻结金额</span>
          <span class="frozen">¥{{ formatAmount(self.dongjie || 0) }}</span>
        </div>
        <div class="detail-item" v-if="self.role === 2">
          <span>当前押金</span>
          <span class="deposit"> ¥{{ self.yajin }}</span>
        </div>
      </div>
    </div>

    <!-- 交易记录选项卡 -->
    <van-tabs v-model="activeTab" line-width="80px">
      <van-tab title="交易记录" :name="self.role === 1 ? 1 : 2">
        <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
          <div v-for="(record, index) in filter()" :key="index" class="record-item">
            <div class="record-left">
              <div class="record-type">{{ record.type === 1 ? '积分交易' : record.type === 2 ? '佣金交易' : record.type === 3 ?
                '罚款交易' : '' }}</div>
              <div class="record-date">{{ formatDate(Number(record.createTime)) }}</div>
            </div>
            <div class="record-right">
              <div class="record-amount" :class="{ 'positive': record.value > 0, 'negative': record.value < 0 }">
                {{ record.amount > 0 ? '+' : '' }}{{ record.value }}
              </div>
              <!-- <div class="record-balance">余额 ¥{{ record.balance }}</div> -->
            </div>
          </div>
        </van-list>
      </van-tab>
      <van-tab :title="self.role === 1 ? '充值记录' : '罚款记录'" :name="self.role === 1 ? 4 : 3">
        <van-list v-model="loading" :finished="finished" finished-text="没有更多了" @load="onLoad">
          <div v-for="(record, index) in filter()" :key="index" class="record-item">
            <div class="record-left">
              <div class="record-type">{{ record.type === 1 ? '积分交易' : record.type === 2 ? '佣金交易' : record.type === 3 ?
                '罚款交易' : '' }}</div>
              <div class="record-date">{{ formatDate(Number(record.createTime)) }}</div>
            </div>
            <div class="record-right">
              <div class="record-amount" :class="{ 'positive': record.value > 0, 'negative': record.value < 0 }">
                {{ record.amount > 0 ? '+' : '' }}{{ record.value }}
              </div>
              <!-- <div class="record-balance">余额 ¥{{ record.balance }}</div> -->
            </div>
          </div>
        </van-list>
      </van-tab>
    </van-tabs>

  </div>
</template>
  
<script>
import dealApi from '@/plugins/api/deal'
import { fuzzyMatch } from '@/plugins/utils/filterArray'
import { formatTime } from "@/plugins/utils/timeUtils";
import configApi from '@/plugins/api/config'
import userApi from '@/plugins/api/user';
export default {
  data() {
    return {
      activeTab: 0,
      loading: false,
      finished: false,
      self: this.$global.self || {
        yijiesuan: 0,
        weijiesuan: 0,
        dongjie: 0,
      },
      deals: [],
      obj: {
        type: 1
      },
      yajin: 0,
    }
  },
  computed: {

  },
  methods: {
    formatAmount(amount) {
      // 金额格式化，保留两位小数
      return Number(amount).toFixed(2).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
    },
    onLoad() {
      // 模拟加载更多数据
      setTimeout(() => {
        this.finished = true
        this.loading = false
      }, 1000)
    },

    async getConfig() {
      const that = this
      const res = await configApi.list()
      if (res.code === 200) {
        console.log('res.data -> ', res.data);
        const config = res.data.find(item => item.name === 'yajin')
        console.log('config -> ', config);
        this.yajin = config.value
      }
    },

    async getUser() {
      const that = this
      await this.getConfig()
      const res = await userApi.all()
      if (res.code === 200) {
        that.self = res.data.find(item => item.id === that.self.id)
        that.getDeal()
      }
    },

    async getDeal() {
      const that = this
      const res = await dealApi.list()
      if (res.code === 200) {
        that.deals = res.data
        that.self.deals = res.data.filter(item => item.userId === that.self.id && !item.status)
        console.log('that.self.deals -> ', that.self.deals);

        that.self = that.initPlayerBalance(that.self)
        console.log(that.self);

      } else {
        that.$toast.fail('获取记录失败')
      }
    },
    initPlayerBalance(item) {
      console.log('押金 -> ', item.yajin);
      item.dongjie = 0
      item.weijiesuan = 0
      let fakuanValue = 0
      const yongjin = item.deals.filter(item => item.type === 2 && !item.status)
      const fakuan = item.deals.filter(item => item.type === 3 && !item.status)

      for (let j = 0; j < fakuan.length; j++) {
        fakuanValue = Number(fakuan[j].value) + fakuanValue
      }

      if (Number(fakuanValue) * -1) {
        if (item.dongjie > 0 && item.dongjie >= Number(fakuanValue) * -1) {
          item.dongjie = item.dongjie + fakuanValue
          fakuanValue = 0
        } else if (item.dongjie > 0 && item.dongjie <= Number(fakuanValue) * -1) {
          item.dongjie = 0
          fakuanValue = fakuanValue + item.dongjie
        }
      }

      if (Number(fakuanValue) * -1) {
        if (item.weijiesuan > 0 && item.weijiesuan >= Number(fakuanValue) * -1) {
          item.weijiesuan = item.weijiesuan + fakuanValue
          fakuanValue = 0
        } else if (item.weijiesuan > 0 && item.weijiesuan <= Number(fakuanValue) * -1) {
          item.weijiesuan = 0
          fakuanValue = fakuanValue + item.weijiesuan
        }
      }

      if (Number(fakuanValue) * -1) {
        item.yajin = Number(item.yajin) + fakuanValue
      }

      for (let i = 0; i < yongjin.length; i++) {
        if (item.yajin <= this.yajin) {
          if (item.yajin + Number(yongjin[i].value) <= this.yajin) {
            item.yajin = Number(yongjin[i].value) + item.yajin
          } else {
            const yj = yongjin[i].value - (this.yajin - item.yajin)
            item.yajin = this.yajin
            if (new Date().getTime() >= yongjin[i].jiesuanTime) {
              item.weijiesuan = Number(yj) + item.weijiesuan
            } else {
              item.dongjie = Number(yj) + item.dongjie
            }
          }

        } else {
          if (new Date().getTime() >= yongjin[i].jiesuanTime) {
            item.weijiesuan = Number(yongjin[i].value) + item.weijiesuan
          } else {
            item.dongjie = Number(yongjin[i].value) + item.dongjie
          }
        }
      }

      return item

    },

    formatDate(timestamp) {
      return formatTime(timestamp)
    },
    filter() {
      console.log(this.self.id);
      const add = this.self.role
      const obj = {
        userId: this.self.id,
        type: this.activeTab
      }
      console.log(fuzzyMatch(this.deals, obj));

      return fuzzyMatch(this.deals, obj).sort((a, b) => b.createTime - a.createTime)
    },

  },
  mounted() {

    // 初始化数据
    if (!this.$global.self) {
      console.warn('全局self对象未定义，使用默认数据')
    }
    this.getUser()
  }
}
</script>
  
<style lang="scss" scoped>
.account-page {
  padding: 16px;
  background: #fff;
  // height: 100%;
}

.balance-card {
  background: linear-gradient(135deg, #1989fa, #36d1dc);
  border-radius: 12px;
  padding: 20px;
  color: white;
  margin-bottom: 16px;
  box-shadow: 0 4px 12px rgba(25, 137, 250, 0.2);

  .balance-header {
    font-size: 16px;
    opacity: 0.9;
    margin-bottom: 8px;
  }

  .balance-amount {
    font-size: 28px;
    font-weight: bold;
    margin-bottom: 20px;
  }

  .balance-details {
    background: rgba(255, 255, 255, 0.2);
    border-radius: 8px;
    padding: 12px;
  }

  .detail-item {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    font-size: 14px;

    &:last-child {
      margin-bottom: 0;
    }

    .frozen {
      color: #ffe58f;
    }

    .deposit {
      color: #a0f0a0;
    }
  }
}

.record-item {
  display: flex;
  justify-content: space-between;
  padding: 16px;
  border-bottom: 1px solid #f5f5f5;

  .record-left {
    .record-type {
      font-size: 16px;
      color: #333;
      margin-bottom: 6px;
    }

    .record-date {
      font-size: 12px;
      color: #999;
    }
  }

  .record-right {
    text-align: right;

    .record-amount {
      font-size: 16px;
      font-weight: 500;
      margin-bottom: 6px;

      &.positive {
        color: #07C160;
      }

      &.negative {
        color: #F56C6C;
      }
    }

    .record-balance {
      font-size: 12px;
      color: #999;
    }
  }
}

.empty-tip {
  text-align: center;
  color: #999;
  padding: 40px 0;
  font-size: 14px;
}

::v-deep .van-tabs__line {
  background-color: #1989fa;
}

::v-deep .van-tab {
  font-size: 15px;
}
</style>